<?php

namespace app\admin\controller\bonus;

use app\admin\model\Assistant;
use app\common\controller\Backend;
use EasyWeChat\Factory;
use Endroid\QrCode\QrCode;
use PHPExcel;
use think\Db;
use think\Session;

/**
 * 优惠券管理
 *
 * @icon fa fa-circle-o
 */
class Typebonus extends Backend
{
    
    /**
     * Typebonus模型对象
     * @var \app\admin\model\bonus\Typebonus
     */
    protected $model = null;
    protected $modelData = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\bonus\Typebonus;
        $this->modelData = new \app\admin\model\bonus\Userbonus;
        $this->view->assign("orderTypeList", $this->model->getOrderTypeList());
        $this->view->assign("goodsTypeList", $this->model->getGoodsTypeList());
        $this->view->assign("sendTypeList", $this->model->getSendTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['type_id','type_name','type_money','order_type','goods_type','send_type','send_start_date','send_end_date','use_start_date','use_end_date','day_time']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                //删除分类
                $this->modelData->where(['bonus_type_id'=>['in',$ids]])->delete();
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                try {
                    if($params['file'] == 1)
                    {
                        unset($params['file'],$params['type_name'],$params['type_money']);
                        $params['use_end_date'] = strtotime($params['use_end_date']);
                        //修改未领取的优惠券
                        $result = $this->modelData->where(['bonus_type_id'=>$ids,'user_id'=>0])->update($params);
                        if ($result !== false) {
                            $this->success('修改成功！','');
                        } else {
                            $this->error($row->getError());
                        }
                    }

                    if($params['file'] == 2){
                        //修改已领取未使用的优惠券
                        unset($params['file'],$params['type_name'],$params['type_money']);
                        $params['use_end_date'] = strtotime($params['use_end_date']);
                        //修改未领取的优惠券
                        $result = $this->modelData->where(['bonus_type_id'=>$ids,'order_id'=>['>',1],'use_end_date'=>['>',time()],'user_id'=>['>',1]])->update($params);
                        if ($result !== false) {
                            $this->success('修改成功！','');
                        } else {
                            $this->error($row->getError());
                        }
                    }

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('修改成功！','');
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     *  发放优惠券
     */
    public function coupon($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            //红包数量
            $params = $this->request->post("row/a");
            if($params['action'] == 2 && !$params['userid'])
            {
                $this->error('请选择企业微信收取人');
            }
            if($params['num'] < 1 || !$params['num'] || $params['num'] > 100000)
            {
                $this->error('请填写大于0的数量,或数量不要大于10万');
            }
            /* 生成红包序列号 */
            $num = '10'.date('md').'0';
            $data = [];
            for ($i = 0, $j = 0; $i < $params['num']; $i++)
            {
                $bonus_sn = ($num + $i) . str_pad(mt_rand(0, 9999), 4, '0', 0);
                $data[$i] = [
                    'bonus_type_id'=>$ids,
                    'bonus_sn'=>$bonus_sn,
                    'use_end_date'=>$row['use_end_date'],
                    'goods_id'=>$row['goods_id'],
                    'source'=>$params['source'],
                ];
                $j++;
            }
            // 启动事务
            Db::startTrans();
            try{
                $count = ceil(count($data) / 10);
                for ($i=1;$i<=$count;$i++){
                    $offset=($i -1)*(10);
                    $array=array_slice($data,$offset,10);
                    $this->modelData->saveAll($array);
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('数据重复。','',$e->getMessage());
            }
            if($params['file'] == 1)
            {
                //下载到本地
                if($params['action'] == 1)
                {
                    $url = $this->export($data,'',15000, $row['type_name'],$row['url'],$params['source']);
                }else{
                    $this->export($data,$params['userid'],15000,$row['type_name'],$row['url'],$params['source']);
                    $url = '';
                }
            }else{
                $name = $this->auth->username."-".date('m-d').'-'.$row['type_name'];
                //设置脚本的最大执行时间，设置为0则无时间限制
                set_time_limit(0);
                ini_set('max_execution_time', '0');
                $filename = ROOT_PATH . 'public/admin/qrcode/' . $name . '.zip';
                $Zip = new \ZipArchive();
                if ($Zip->open($filename, \ZIPARCHIVE::CREATE) !== TRUE) {
                    exit('无法打开文件，或者文件创建失败');
                    return 0;
                }
                //生成图片打包
                foreach ($data as $key=>$value)
                {
                    //保存图片
                    $url = $row['url'].$value['bonus_sn'].'&source='.$params['source'];
                    $qrCode =  new QrCode();//创建生成二维码对象
                    $qrCode->setText($url)
                        ->setSize(230)
                        ->setPadding(10)
                        ->setErrorCorrection('high')
                        ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
                        ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
                        ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG);
                    //>>>>>>>直接输出到浏览器>>>>>>>>>>
                    //header("Content-type: image/png");
                    //$qrCode->render(); //输入到浏览器
                    //>>>>>>>直接输出到浏览器>>>>>>>>>>
                    //>>>>>>>>>保存文件>>>>>>>>>>>
                    $path = ROOT_PATH . 'public/admin/qrcode/'.$this->auth->user_id.$value['bonus_sn']."--".($key+1).".png";
                    $qrCode->save($path); //保存文件
                    //>>>>>>>>>保存文件>>>>>>>>>>>
                    $Zip->addFromString(($key+1).'.png', file_get_contents($path));
                    if (file_exists($path)) {
                        unlink($path);//删除文件
                    }
                }
                $Zip->close();
                $fp = fopen($filename, "r");
                $file_size = filesize($filename);//获取文件的字节
                $buffer = 1024; //设置一次读取的字节数，每读取一次，就输出数据（即返回给浏览器）
                $file_count = 0; //读取的总字节数
                while (!feof($fp) && $file_count < $file_size) {
                    fread($fp, $buffer);
                    $file_count += $buffer;
                }
                fclose($fp);
                $url = "admin/qrcode/".$name.".zip";
                //下载到本地
                if($params['action'] == 2)
                {
                    //上传到企业微信临时文件
                    if($params['userid'])
                    {
                        $config = Assistant::config();
                        $app = Factory::work($config);
                        $res = $app->media->uploadFile($filename);
                        //发送文件给操作人
                        if($res['errcode'] == 0 ){
                            $token = $app->access_token->getToken();//获取企业微信token
                            $urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
                            $paramsRes = [
                                'touser'=>$params['userid'],
                                'msgtype'=>'file',
                                'agentid'=>$config['agent_id'],
                                'file'=>[
                                    'media_id'=>$res['media_id']
                                ],
                                'safe'=>0
                            ];
                            $response = \fast\Http::post($urls,json_encode($paramsRes));
                            $data['media_id'] = $res['media_id'];
                            $response = json_decode($response,true);
                            if($response['errcode'] != 0)
                            {
                                return false;
                            }
                            if (file_exists($filename)) {
                                unlink($filename);//删除文件
                            }
                            $url = '';
                        }
                    }
                }
            }

            if($params['res'] == 2)
            {
                $this->error('优惠券生成成功！',$url);
            }
            $this->success('优惠券生成成功！',$url);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function export(array $list,$userid = null,$limit=1000,$name='',$url = null,$source = null)
    {
        $objPHPExcel = new PHPExcel();
        $count = ceil(count($list) / $limit);
        $row = $objPHPExcel->setactivesheetindex(0);
        //列为文本
        $row->getStyle('A')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        for ($i=1;$i<=$count;$i++){
            $row->setTitle("$i");
            $offset = ($i-1) * $limit;
            $array = array_slice($list,$offset,$limit);
            foreach ($array as $k => $v) {
                $row->setcellvalue('A'.($k+1), $url.$v['bonus_sn'].'&source='.$source);
                $row->getColumnDimension('A')->setWidth(100);
            }
            if($i <= $count-1)
            {
                //创建一个新的工作空间(sheet)
                $objPHPExcel->createSheet();
                $row = $objPHPExcel->setactivesheetindex($i);
                $row->setTitle("$i");
                //列为文本
                $row->getStyle('A')->getNumberFormat()
                    ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
            }
        }
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $date = date('Y-m-d H-i-s',time());
        $filename = $this->auth->username.'-'.$name.'-'.$date.'.xlsx';
        $objWriter->save('./admin/bonus/xlsx/'.$filename);
        //添加操作日志
        $data = [
            'text' => $this->auth->username.'生成'.$name.'/'.count($list).'个',
            'url' => '/admin/bonus/xlsx/'.$filename,
        ];
        //上传到企业微信临时文件
        if($userid)
        {
            $config = Assistant::config();
            $app = Factory::work($config);
            $path = ROOT_PATH . 'public/admin/bonus/xlsx/'.$filename;
            $res = $app->media->uploadFile($path);
            //发送文件给操作人
            if($res['errcode'] == 0 ){
//                unlink($path);
                $token = $app->access_token->getToken();//获取企业微信token
                $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
                $params = [
                    'touser'=>$userid,
                    'msgtype'=>'file',
                    'agentid'=>$config['agent_id'],
                    'file'=>[
                        'media_id'=>$res['media_id']
                    ],
                    'safe'=>0
                ];
                $response = \fast\Http::post($url,json_encode($params));
                $data['media_id'] = $res['media_id'];
                $data['text'] .='发送给'.$this->auth->username;
                $response = json_decode($response,true);
                if($response['errcode'] != 0)
                {
                    return false;
                }
            }
            return true;
        }
        return $data['url'];
    }
}
